/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Articulos;
import entities.Logs;
import entities.UnidadesAlojamiento;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;

/**
 * @author Siaat
 */
public class AltaArticulos extends JPanel {

    private Articulos articulo;
    private Logs logs;
    private boolean editando = false;
    private Usuarios usuario;
    public static JFrame frame;

    /**
     *
     */
    public AltaArticulos(Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        //Dejar sin seleccionar ningún elemento para la búsqueda
        buscarArticulosComboBox.setSelectedIndex(-1);
        this.usuario = usuario;
    }

    private Integer getIDArticulo(String marca, String numeroSerie) {
        Query queryIDArticulo;
        Articulos art;
        queryIDArticulo = entityManager.createNamedQuery("Articulos.findByMarcaNumeroSerie");
        queryIDArticulo.setParameter("marca", marca);
        queryIDArticulo.setParameter("numeroSerie", numeroSerie);
        art = (Articulos) queryIDArticulo.getSingleResult();
        return art.getIdArticulo();
    }

    public JFrame getFrame() {
        return frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Articulos a ORDER BY a.tipoArticulo ASC ,a.marca ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        unidadesAlojamientoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        tipoArticuloLabel = new javax.swing.JLabel();
        marcaLabel = new javax.swing.JLabel();
        numeroSerieLabel = new javax.swing.JLabel();
        colorLabel = new javax.swing.JLabel();
        descripcionLabel = new javax.swing.JLabel();
        ubicacionFisicaLabel = new javax.swing.JLabel();
        tipoArticuloField = new javax.swing.JTextField();
        marcaField = new javax.swing.JTextField();
        numeroSerieField = new javax.swing.JTextField();
        colorField = new javax.swing.JTextField();
        descripcionField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        ubicacionFisicaComboBox = new javax.swing.JComboBox();
        ayudaLabel = new javax.swing.JLabel();
        exportarExcelButton = new javax.swing.JButton();
        buscarButton = new javax.swing.JButton();
        cancelarBusquedaButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        buscarArticulosComboBox = new javax.swing.JComboBox();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoArticulo}"));
        columnBinding.setColumnName("Tipo Articulo");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${marca}"));
        columnBinding.setColumnName("Marca");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${numeroSerie}"));
        columnBinding.setColumnName("Numero Serie");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${color}"));
        columnBinding.setColumnName("Color");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descripcion}"));
        columnBinding.setColumnName("Descripcion");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${ubicacionFisica}"));
        columnBinding.setColumnName("Ubicacion Fisica");
        columnBinding.setColumnClass(entities.UnidadesAlojamiento.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);

        tipoArticuloLabel.setText("Tipo Articulo:");

        marcaLabel.setText("Marca:");

        numeroSerieLabel.setText("Numero Serie:");

        colorLabel.setText("Color:");

        descripcionLabel.setText("Descripcion:");

        ubicacionFisicaLabel.setText("Ubicacion Fisica:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.tipoArticulo}"), tipoArticuloField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), tipoArticuloField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.marca}"), marcaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), marcaField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.numeroSerie}"), numeroSerieField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), numeroSerieField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.color}"), colorField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), colorField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.descripcion}"), descripcionField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), descripcionField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(formListener);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), borrarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        borrarButton.addActionListener(formListener);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, unidadesAlojamientoList, ubicacionFisicaComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ubicacionFisica}"), ubicacionFisicaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), ubicacionFisicaComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        buscarButton.setBackground(new java.awt.Color(1, 154, 210));
        buscarButton.setForeground(new java.awt.Color(255, 255, 255));
        buscarButton.setText("Buscar");
        buscarButton.addActionListener(formListener);

        cancelarBusquedaButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarBusquedaButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarBusquedaButton.setText("Cancelar Busqueda");
        cancelarBusquedaButton.addActionListener(formListener);

        jLabel1.setText("Filtrar Artículos Por Ubicación");

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, unidadesAlojamientoList, buscarArticulosComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tipoArticuloLabel)
                    .addComponent(marcaLabel)
                    .addComponent(numeroSerieLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(nuevoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(buscarArticulosComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(borrarButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(buscarButton, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cancelarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(guardarButton))
                            .addComponent(cancelarBusquedaButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tipoArticuloField)
                            .addComponent(marcaField)
                            .addComponent(numeroSerieField, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(colorLabel)
                            .addComponent(descripcionLabel)
                            .addComponent(ubicacionFisicaLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(descripcionField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ubicacionFisicaComboBox, 0, 266, Short.MAX_VALUE)
                            .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING))))
                .addGap(42, 42, 42))
            .addComponent(masterScrollPane)
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {borrarButton, cancelarButton, guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tipoArticuloLabel)
                        .addGap(18, 18, 18)
                        .addComponent(marcaLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(colorLabel)
                            .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(descripcionLabel)
                            .addComponent(descripcionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(ubicacionFisicaLabel)
                            .addComponent(ubicacionFisicaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(tipoArticuloField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(marcaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(numeroSerieField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(numeroSerieLabel))))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cancelarBusquedaButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buscarButton)
                        .addComponent(jLabel1)
                        .addComponent(buscarArticulosComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(guardarButton)
                        .addComponent(cancelarButton)
                        .addComponent(borrarButton)
                        .addComponent(nuevoButton))
                    .addComponent(ayudaLabel)
                    .addComponent(exportarExcelButton, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaArticulos.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaArticulos.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaArticulos.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                AltaArticulos.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaArticulos.this.exportarExcelButtonActionPerformed(evt);
            }
            else if (evt.getSource() == buscarButton) {
                AltaArticulos.this.buscarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarBusquedaButton) {
                AltaArticulos.this.cancelarBusquedaButtonActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaArticulos.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                AltaArticulos.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    /*
     * @param evt que se recibe al apretar el boton la funcion
     * cancelarButtonActionPerformed realiza un rollback a la operacion que
     * estaba en curso, desabilita los botones en pantalla y limpia los campos.
     *
     *
     */
    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();
        editando = false;
    }//GEN-LAST:event_cancelarButtonActionPerformed

    /*
     *
     * esta funcion limpia todos los campos seteandolos en string vacios y los
     * combobox en -1 para que no aparezca nada seleccionado
     */
    private void limpiarBotones() {
        tipoArticuloField.setText("");
        marcaField.setText("");
        numeroSerieField.setText("");
        colorField.setText("");
        descripcionField.setText("");
        ubicacionFisicaComboBox.setSelectedIndex(-1);
    }

    /**
     * esta funcion realiza el borrado de un articulo seleccionado, preguntando
     * si se desea borrar el articulo previamente.
     */
    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar el borrado del Articulo?", "Borrado de Articulo", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
            int[] selected = masterTable.getSelectedRows();
            List<entities.Articulos> toRemove = new ArrayList<entities.Articulos>(selected.length);
            for (int idx = 0; idx < selected.length; idx++) {
                articulo = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                toRemove.add(articulo);
                logs = new Logs();
                logs.setUsuario(usuario);
                logs.setearObservaciones("Borrado", "Articulos", articulo.getIdArticulo(), "AltaArticulos");
                entityManager.persist(logs);
                entityManager.remove(articulo);
            }
            list.removeAll(toRemove);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
            cancelarButtonActionPerformed(null);
        }
    }//GEN-LAST:event_borrarButtonActionPerformed

    /**
     * llama a la funcion habilitarBotones y ademas esta funcion permite
     * insertar un nuevo articulo en la base de datos
     */
    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        habilitarBotones(true);

        articulo = new entities.Articulos();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(articulo);
        list.add(articulo);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        borrarButton.setEnabled(false);
        tipoArticuloField.requestFocus();
    }//GEN-LAST:event_nuevoButtonActionPerformed
    /*
     * @param art es del tipo Articulos el cual se utiliza para chequear si ya
     * existe el articulo en la list de articulos @return boolean retorna false
     * si no se encontro un duplicada y true si se encontro.
     */

    private boolean existeArticulo(Articulos art) {
        int cont = 0;
        for (Articulos articulos : list) {
            if (articulos.getMarca().equalsIgnoreCase(art.getMarca()) && articulos.getNumeroSerie().equalsIgnoreCase(art.getNumeroSerie())) {
                cont++;
            }
        }
        if (cont < 2) {
            return false;
        }
        return true;
    }

    /**
     * la funcion guardarButtonActionPerformed permite guardar un Articulo nuevo
     * en la base de datos o realizar una actualizacion
     */
    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if ((ubicacionFisicaComboBox.getSelectedIndex() == -1) || ("".equals(tipoArticuloField.getText())) || ("".equals(marcaField.getText())) || ("".equals(numeroSerieField.getText())) || ("".equals(colorField.getText())) || ("".equals(descripcionField.getText()))) {
            JOptionPane.showMessageDialog(this, "Debe completar todos los campos", "Atención", JOptionPane.ERROR_MESSAGE, null);
        } else {

            try {
                articulo = list.get(masterTable.getSelectedRow());
                logs = new Logs();
                logs.setUsuario(usuario);
                if (existeArticulo(articulo)) {
                    JOptionPane.showMessageDialog(this, "Ya existe el articulo que desea ingresar, "
                            + "MARCA y NUMERO DE SERIE duplicado", "Atención", WIDTH, null);
                    marcaField.requestFocus();
                } else {
                    if (editando) {
                        entityManager.merge(articulo);
                    }
                    if (articulo.getIdArticulo() == null) {
                        entityManager.getTransaction().commit();
                        entityManager.getTransaction().begin();
                        Integer idArticulo = getIDArticulo(articulo.getMarca(), articulo.getNumeroSerie());
                        logs.setearObservaciones("Alta", "Articulos", idArticulo, "AltaArticulos");
                    } else {
                        logs.setearObservaciones("Modificación", "Articulos", articulo.getIdArticulo(), "AltaArticulos");
                    }
                    entityManager.persist(logs);
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    cancelarButtonActionPerformed(null);
                }
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.Articulos> merged = new ArrayList<entities.Articulos>(list.size());
                for (entities.Articulos a : list) {
                    merged.add(entityManager.merge(a));
                }
                list.clear();
                list.addAll(merged);
            }
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    /**
     *
     * @param estado va a ser el estado a tomar de los componentes en la view,
     * algunos componentes toman el valor inverso.
     */
    private void habilitarBotones(boolean estado) {
        tipoArticuloField.setEnabled(estado);
        marcaField.setEnabled(estado);
        numeroSerieField.setEnabled(estado);
        colorField.setEnabled(estado);
        descripcionField.setEnabled(estado);
        ubicacionFisicaComboBox.setEnabled(estado);
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);
        buscarArticulosComboBox.setEnabled(!estado);
        buscarButton.setEnabled(!estado);
        cancelarBusquedaButton.setEnabled(!estado);
        borrarButton.setEnabled(estado);
        cancelarButton.setEnabled(estado);
        guardarButton.setEnabled(estado);
    }

    /**
     * llama a habilitarBotones al seleccionar un elemento de la masterTable
     */
    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
    }//GEN-LAST:event_masterTableMouseClicked
    /**
     * muestra un mensaje de ayuda al pasar el mouse por arriba del cuadro de
     * ayuda
     */
    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar artículos");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Articulos").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed

    private void buscarArticulosPorCliente(UnidadesAlojamiento ua) {
        Query query = entityManager.createNamedQuery("Articulos.findByUnidadAlojamiento");
        query.setParameter("idUnidadAlojamiento", ua);
        List<Articulos> articulosList = query.getResultList();
        list.clear();
        list.addAll(articulosList);
        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No se encontro ningun resultado, revise los campos de busqueda", "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        }

    }

    private void buscarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarButtonActionPerformed
        if (buscarArticulosComboBox.getSelectedIndex() == -1) {
            cancelarButtonActionPerformed(null);
        } else {
            UnidadesAlojamiento ua = (UnidadesAlojamiento) buscarArticulosComboBox.getSelectedItem();
            buscarArticulosPorCliente(ua);
        }
    }//GEN-LAST:event_buscarButtonActionPerformed

    private void cancelarBusquedaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarBusquedaButtonActionPerformed
        Query query = entityManager.createNamedQuery("Articulos.findAll");
        list.clear();
        List<Articulos> articulosList = query.getResultList();
        list.addAll(articulosList);
        buscarArticulosComboBox.setSelectedIndex(-1);
    }//GEN-LAST:event_cancelarBusquedaButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JComboBox buscarArticulosComboBox;
    private javax.swing.JButton buscarButton;
    private javax.swing.JButton cancelarBusquedaButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField colorField;
    private javax.swing.JLabel colorLabel;
    private javax.swing.JTextField descripcionField;
    private javax.swing.JLabel descripcionLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private java.util.List<entities.Articulos> list;
    private javax.swing.JTextField marcaField;
    private javax.swing.JLabel marcaLabel;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JTextField numeroSerieField;
    private javax.swing.JLabel numeroSerieLabel;
    private javax.persistence.Query query;
    private javax.swing.JTextField tipoArticuloField;
    private javax.swing.JLabel tipoArticuloLabel;
    private javax.swing.JComboBox ubicacionFisicaComboBox;
    private javax.swing.JLabel ubicacionFisicaLabel;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList;
    private javax.persistence.Query unidadesAlojamientoQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    /**
     *
     */
    public void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        AltaArticulos.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new AltaArticulos(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Inventario   -   Articulos   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
